#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "reg.pb-c.h"
#include "lookup.pb-c.h"

struct member
{
	char name[10];
	char passwd[10];
};

enum type
{
	reg = 1,
	login,
	lookup,
	quit
};

int connect_to_host(int port,const char *ipServer)
{
	int sock = 0;
	int ret = 0;
	struct sockaddr_in addr;

	memset(&addr,0,sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = inet_addr(ipServer);

	sock = socket(AF_INET,SOCK_STREAM,0);
	if(sock == -1)
	{
		perror("socket");
		return -1;
	}

	ret = connect(sock,(struct sockaddr *)&addr,sizeof(struct sockaddr));
	if(ret == -1)
	{
		perror("connect");
		return -1;
	}

	return sock;

}

enum type  menu()
{
	int sel = 0;
	printf("please input your choice\n");
	printf("1--register,2--login\n");
	printf("3--lookup,4--quit\n");

	scanf("%d",&sel);
	return sel;
}

int regist(int sock,int type)
{

	 int ret = 0;
	 struct member mem;
	 memset(&mem,0,sizeof(struct member));
	 scanf("%s%s",mem.name,mem.passwd);

	 Info temp = INFO__INIT;
	 void *buf = NULL;
	 unsigned int len = 0;
	 Info *msg = NULL;

	 temp.name = malloc(10);
	 temp.passwd = malloc(10);

	 strcpy(temp.name,mem.name);
	 strcpy(temp.passwd,mem.passwd);
	 len = info__get_packed_size(&temp);

	 buf = malloc(len + 4);
	 info__pack(&temp,buf + 4);
	 if(type == 1)
	 {
		 memcpy(buf,"regi",4);
	 }else if(type == 2)
	 {
		 memcpy(buf,"logi",4);
	 }
	 ret = send(sock,buf,len + 4,0);
	 if(ret == -1)
	 {
		 perror("send");
		 return -1;
	 }
	 free(buf);

	 return 0;
}

int find_by_time(int sock)
{

	int year = 0,month = 0,day = 0;
	int ret = 0;
	int len = 0;
	void *buf = NULL;

	Find temp = FIND__INIT;

	temp.year = 2017;
	temp.month = 3;
	temp.day = 21;

	len = find__get_packed_size(&temp);
	printf("len = %d\n",len);

	buf = malloc(len + 4);
	find__pack(&temp,buf + 4);
	memcpy(buf,"look",4);

	ret = send(sock,buf,len+4,0);
	if(ret == -1)
	{
		perror("send");
		return -1;
	}
	return 0;
}

int main()
{
	
	int sock = 0;
	int sel = 0;
	int ret = 0;

	sock = connect_to_host(6868,"192.168.0.151");
	if(sock == -1)
	{
		printf("can't to connect server\n");
		exit(-1);
	}

	sel = menu();
	while(sel != quit)
	{
		switch(sel)
		{
			case reg:
				     ret = regist(sock,1);
					 if(ret != 0)
					 {
						printf("register error\n");
					 }
					 break;

			case login:ret = regist(sock,2);
					   if(ret != 0)
					   {
						   printf("login error\n");
					   }
					   break;
			case lookup:
					   ret = find_by_time(sock);
					   if(ret != 0)
					   {
						   printf("find send ok\n");
					   }
				       
				       break;
			default:
				printf("input error\n");
		}
		sel = menu();
	}


	close(sock);
	return 0;
}


